const { dir } = require('node:console')
var fs = require('node:fs')
var path = require('node:path')
function getModuleInfo(file, dirname = null) {
  if (!dirname) {
    dirname = path.dirname(path.resolve(file))
  }
  var absolutePath = path.resolve(dirname, file)
  var code = fs.readFileSync(absolutePath, 'utf-8')
  // 获取依赖 更新 modules
  var innerModules = getInnerModules(code)

  return {
    file,
    moduleNames: innerModules,
    code,
    dirname: path.dirname(absolutePath)
  }
}

function getInnerModules(code) {
  var regex = /require\(["']([^"']+)["']\)/g
  var matches
  var result = []

  while ((matches = regex.exec(code)) !== null) {
    result.push(matches[1])
  }
  return result
}

/**
 * 生成 bundle 文件
 */
function createBundle(entry) {
  var entryModule = getModuleInfo(entry)
  var modules = {
    [entryModule.file]: entryModule.code
  }
  deepSearchModule(modules, entryModule)
  var bundle = '(function(){var modules = ' + JSON.stringify(modules) + ';function require(file) {var module = {exports: {}};var exports = module.exports;(function() {eval(modules[file])})();return module.exports;}require(\'' + entry + '\');})();'
  return bundle
}

/**
 * 通过 深搜 遍历依赖
 */
function deepSearchModule(totalModules = {}, moduleInfo) {
  moduleInfo.moduleNames.forEach(function (item) {
    var module = getModuleInfo(item, moduleInfo.dirname)
    // ！！！ 简单去重判定，未解决相对路径重名问题
    var isHad = Object.keys(totalModules).find(function (i) {
      return i === module.file
    })
    if (isHad !== -1) {
      totalModules[module.file] = module.code
    }
    deepSearchModule(totalModules, module)
  })
}

module.exports = function webpack(config) {
  var bundle = createBundle(config.entry)
  !fs.existsSync(config.output.path) && fs.mkdirSync(config.output.path)
  fs.writeFileSync(path.resolve(config.output.path, config.output.filename), bundle)
}

// console.log(createBundle('./main.js'))